package com.gaohe.Filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class loginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        设置白名单
        String[] paths = {
                ".html",
                ".htm",
                ".css",
                ".js",
                ".ttf",
                ".woff",
                ".jpg",
                ".png",
                ".mp4",
                "/manager/login",
//                多余的两次拦截，需要手动添加到白名单
                "/manager/getName",
                "/manager/count",
//                退出
                "/manager/logout",
//                main界面的主要功能
                "/goods/search",
                "/user/buy",
                "/user/getName",
//                user登录
                "/user/login",
                "/user/register",
//                注册验证码
                "/user/code",
//                突出
                "/user/logout",
//                未登录进行购买：获取session进行判断
                "/user/getSession",
//                main中的分页
                "/goods/search"
        };
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uri = request.getRequestURI();//获取地址栏的uri
//        对白名单中的数据进行一一判断,是否是白名单格式
//        对白名单的资源放行
        for (String path : paths) {
            if (uri.contains(path)) {
//                System.out.println(uri+"    放行");
                filterChain.doFilter(request, response);
                return;
            }
        }
//        对登录成功的用户放行，根据session判断
        HttpSession session = request.getSession();
        if (session.getAttribute("manager") != null) {//
            System.out.println("登录成功 放行" + uri);
            filterChain.doFilter(request, response);
            return;
        } else {//没有含有权限的session的情况进入管理页面，进行拦截
            response.getWriter().write("notlog");
            return;
        }

    }

    @Override
    public void destroy() {
        System.out.println("销毁");
    }
}
